import Taro, { Component } from '@tarojs/taro'
import parseHtml from 'mini-html-parser2'; //如果是微信小程序   需要注释这一行以及其使用的地方   不然会报错
import { View, Swiper, SwiperItem, Image, Text, RichText } from '@tarojs/components'

import './index.scss'

import Collect from '../../components/collect'
import Tabs from '../../components/tabs'
import AddCart from '../../components/addCart'
import Comment from '../../components/comment'
import Kill from '../../components/goodsDatil/kill'
import GoodSwiper from '../../components/goodsDatil/goodSwiper'
import GoodsClose from '../../components/goodsClose'
import List from '../../components/list'
import PinTuanModal from '../../components/pinTuanModal'
import Authorize from '../../components/authorize/authorize'

import api from '../../service/api'
import { get as getGlobalData } from '../../static/js/global_data'



export default class Index extends Component {
    config = {
        navigationBarTitleText: '商品详情'
    }
    constructor() {
        super(...arguments)
    }
    state = {
        goodsInfo: null,//商品信息
        goodsImg: [],//商品图片
        richTxt: null,//富文本信息--服务器拿到富文本转化为数组
        imgUrl: getGlobalData('domainImg'),//图片前缀
        tabsNum: 0,//tabs
        lvgg: null,//规格

        salemodel: null,//页面跳转过来的时候指定的活动信息，活动列表中没有的话则不显示
        activeArr: [],//活动列表
        sType: null,//活动入口的值
        pinTuanData: null,//拼团活动
        pinTuanAll: null,//正在拼团的活动
        isPayOne: 0,//是否单独购买
        shopInfo: getGlobalData('shopInfo')
    }
    componentWillMount() {
        console.log(this.$router.params)
        /*GOODS_ATTR //1表示实物，2表示服务项目，3表示套餐卡，4台位*/
        this.setState({
            goodsAttr: this.$router.params.goodsAttr
        })
    }

    componentDidMount() {
        this.getGoodsDatils()
    }

    getGoodsDatils() {
        /* 设置请求数据 GOODS_ATTR //1表示实物，2表示服务项目，3表示套餐卡，4台位*/
        let { goodsId, SaleTypeNo} = this.$router.params;
        // let str = `gid&ShopNo`
        // let params = {
        //     bNo: 701,
        //     gid: goodsId,
        //     isGoodsImg: "1",
        //     isgroupshop: SaleTypeNo == 'pinTuan' ? '1' : '0',
        //     mebno: getGlobalData('C_MB_NO'),//用户信息id
        //     ShopNo: getGlobalData('SHOP_NO'),
        // }
        let str = `ShopNo&gid&mebno`
        let params = {
            bNo: 'goods001',
            ShopNo: getGlobalData('SHOP_NO'),
            gid: goodsId,
            mebno: getGlobalData('C_MB_NO'),//用户信息id
        }
        this.resData(str, params)
    }

    isJsonStr(str) {
        /* 判断是否未JSON字符串 */
        try {
            if (typeof JSON.parse(str) == "object") {
                return true;
            }
        } catch (e) { }
        return false;
    }

    getGoodsDatilsGG(myData) {
        /* 从规格详情发起请求更新商品数据 */
        let { SaleTypeNo } = this.$router.params;
        let { goodsInfo, isPayOne } = this.state;
        let str = `Spv1&GbId&ShopNo`
        let params = {
            bNo: '701b',
            isgroupshop: (SaleTypeNo == 'pinTuan' && isPayOne == 0) ? '1' : '0',
            GbId: goodsInfo.N_GB_ID,
            ShopNo: getGlobalData('SHOP_NO'),
        }
        Taro.showLoading({ title: '加载中...' })
        api.get(str, Object.assign(params, myData), (res) => {
            Taro.hideLoading()
            this.setState({
                goodsInfo: res.goods[0],
                salemodel: this.isJsonStr(res.goods[0].salemodel) ? JSON.parse(res.goods[0].salemodel[0]) : null
            }, () => {
                this.changeShopCloseData()
            })
            this.setRichHtml(res.goods[0].GOODS_DETAIL)
        }, (res) => {
            Taro.hideLoading()
            Taro.showToast({
                title: res.msg,
                icon: 'none',
                duration: 2000
            })
        })
    }
    // 商品详情
    resData(str, par) {
        let { SaleTypeNo } = this.$router.params;
        Taro.showLoading({ title: '加载中...' })
        api.get(str, par, (res) => {
            console.log(res,"=========redredd==========================")
            Taro.hideLoading()
            let salemodel = res.data.actTypes;
            let newAct = null
            salemodel.map((val) => {
                /* 如果是全场活动时只在促销行展示 价格栏目不做展示 */
                /* 并且在活动列表中没用活动入口指定的活动时，价格栏目中不做展示 */
                // if (val.SaleTypeNo == SaleTypeNo && SaleTypeNo != 3) {
                  //  newAct = val
                // }
                 if (newAct == null) {
                    newAct = val.actId
                 }else{
                    newAct += ','+val.actId
                 }
            })
            //if(!res.imageList){res.imageList = []}
            // res.GoodsImgs.map((item) => {
            //     item.pic = item.PICNAME
            // })
            console.log('SaleTypeNo: ---' + SaleTypeNo)
            this.setState({
                goodsInfo: res.data,
                goodsImg: res.data.imageList,
                salemodel: res.data.activeType,
                activeArr: salemodel,
                sType: newAct,
                pinTuanData: res.ptOverStock == 1 ? res.ptMembers : null,
                pinTuanAll: res.data.activeType,
                lvgg: res.data.specList,//规格
            })
            console.log(this.state.goodsImg)
            this.setRichHtml(res.data.goodsDetail)
        }, (res) => {
            Taro.hideLoading()
            Taro.showToast({
                title: res.msg,
                icon: 'none',
                duration: 2000
            })
        })
    }

    setRichHtml(h) {
        let html = h.replace(/\<img/gi, '<img style="max-width:100%;height:auto" ');
        if (process.env.TARO_ENV == 'weapp') {
            this.setState({
                richTxt: html
            })
        } else if (process.env.TARO_ENV == 'alipay') {
            parseHtml(html, (err, nodes) => {
                if (!err) {
                    this.setState({
                        richTxt: nodes
                    })
                }
            }) 
        }
    }
    tabChange(index) {
        //得到tabs当前选择的项
        const { goodsInfo } = this.state;
        if (goodsInfo) {
            if (goodsInfo.goodsDefaultId != '') {
                this.setState({
                    tabsNum: index
                })
            }
        }
    }
    // 点击收藏
    onCollect(){
        this.isLogin.isLogin()
    }
    // authorize获取作用域
    getIsLogin(obj){
        console.log(obj)
        if(obj.C_MB_NO){ 
            console.log('登陆后的操作')
        }else{
            this.isLogin = obj
        }	
    }
    // 加入购物车
    onChoose(type, fPrice, joinData = null) {
        this.isLogin.isLogin(() => { 
             /* 由选择订单组件调起结算订单组件 */
            /* 传入拉起组件的方式----type */
            /* 优惠价格----fPrice */
            /* 积分 */
            const { goodsInfo, sType, lvgg ,salemodel} = this.state;
            console.log('salemodel--------------')
           console.log(salemodel)
            let data = {
                type,//订单创建方式
                fPrice: goodsInfo.intPrice,
                integral: goodsInfo.intCount,
                sType,
                lvgg,
                salemodel,
                joinData,//参加拼团的数据
            }
            if (sType == 5) {
                // 如果是积分
                data['fPrice'] = salemodel ? salemodel.saledata.ReallSalePrice : fPrice
            }
            if (type == 2) {
                this.setState({ isPayOne: 1 })
            } else {
                this.setState({ isPayOne: 0 })
            }
            this.shopCloseScope.showCut(data)
        })
    //    this.isLogin()
    }
    joinPinTuan(joinData) {
        /* 参加拼团 */
        let { pinTuanData: { N_GSPrice } } = this.state;
        this.onChoose(4, N_GSPrice, joinData)
    }
    getShopClose(obj) {
        /* 获取结算订单组件作用域 */
        this.shopCloseScope = obj
    }
    changeShopCloseData() {
        /* 更新子组件的信息 */
        const { salemodel } = this.state;
        let d = {
            fPrice: salemodel ? salemodel.saledata.SalePrice : 0,
            integral: (salemodel && salemodel.SaleTypeNo == 5) ? salemodel.saledata.N_IntegralCount : 0,
        }
        this.shopCloseScope.setState(d)
    }
    showPinTuanModal() {
        this.pinTuanModalScope.showCut()
    }
    getPinTuanModal(obj) {
        this.pinTuanModalScope = obj
    }
    // {
    //     !salemodel ? (
    //         /* 无活动 */
    //         sType == 'pinTuan' && pinTuanData ? (
    //             /* 拼团 */
    //             <View className='shopMsg'>
    //                 <Text className='money'>￥{pinTuanData.N_GSPrice}</Text>
    //                 {/* 判断是否有单位 */goodsInfo.unitName ? <Text>/{goodsInfo.unitName}</Text> : ''}
    //                 <Text className='del'>原价:￥{goodsInfo.salearea ? goodsInfo.salearea : goodsInfo.SALE_PRICE}</Text>
    //             </View>
    //         ) : (
    //                 <View className='shopMsg'>
    //                     {/* 如果有规格则优先显示规格价格 */}
    //                     <Text className='money'>￥{goodsInfo.salearea ? goodsInfo.salearea : goodsInfo.SALE_PRICE}</Text>
    //                     {/* 判断是否有单位 */goodsInfo.unitName ? <Text>/{goodsInfo.unitName}</Text> : ''}
    //                 </View>
    //             )
    //     ) : salemodel.SaleTypeNo == 3 ? (
    //         /* 全场满减 */
    //         <View className='shopMsg'>
    //             <Text className='money'>￥{goodsInfo.salearea ? goodsInfo.salearea : goodsInfo.SALE_PRICE}</Text>
    //             {/* 判断是否有单位 */goodsInfo.unitName ? <Text>/{goodsInfo.unitName}</Text> : ''}
    //         </View>
    //     ) : salemodel.SaleTypeNo == 0 ? (
    //         /* 无活动 */
    //         <View className='shopMsg'>
    //             <Text className='money'>￥{goodsInfo.salearea ? goodsInfo.salearea : goodsInfo.SALE_PRICE}</Text>
    //             {/* 判断是否有单位 */goodsInfo.C_UnitName ? <Text>/{goodsInfo.C_UnitName}</Text> : ''}
    //         </View>
    //     ) : salemodel.SaleTypeNo == 5 ? (
    //         /* 积分活动 */
    //         <View className='shopMsg'>
    //             <Text className='money'>￥{salemodel.saledata.ReallSalePrice}</Text>
    //             {/* 判断是否有单位 */goodsInfo.C_UnitName ? <Text>/{goodsInfo.C_UnitName}</Text> : ''}
    //             <Text className='score'>+{salemodel.saledata.N_IntegralCount}积分</Text>
    //             <Text className='del'>原价:￥{goodsInfo.salearea ? goodsInfo.salearea : goodsInfo.SALE_PRICE}</Text>
    //         </View>
    //     ) : salemodel.SaleTypeNo == 12 ? (
    //         /* 打折 */
    //         <View className='shopMsg'>
    //             <Text className='money'>￥{salemodel.saledata.SalePrice}</Text>
    //             {/* 判断是否有单位 */goodsInfo.C_UnitName ? <Text>/{goodsInfo.C_UnitName}</Text> : ''}
    //             <Text className='del'>原价:￥{goodsInfo.salearea ? goodsInfo.salearea : goodsInfo.SALE_PRICE}</Text>
    //         </View>
    //     ) : ''
    // }
   
    render() {
        const { goodsInfo, goodsImg, imgUrl, richTxt, tabsNum, salemodel, activeArr, sType, pinTuanData, pinTuanAll } = this.state;
        return (
            <View className='goodsDatil'>
                {/* 图片 */}
                <GoodSwiper goodsImg={goodsImg}></GoodSwiper>
                <View className='shopbody'>
                    {
                        /* 秒杀 */
                        pinTuanAll == 2 ? <Kill salemodel={goodsInfo} price={goodsInfo.skuList[0].oldPrice} /> : ''
                    }
                    <View className='shopTit'>
                        <View className='shopTitL'> {goodsInfo.goodsName} </View>
                        <View className='shopTitR'>
                            {/* 收藏 */}
                            {goodsInfo ? <Collect gid={goodsInfo.goodsDefaultId} choose={goodsInfo.isCollect} onCollect={this.onCollect.bind(this)} /> : ''}
                        </View>
                    </View>
                   
                    {   
                        pinTuanAll == 0 ? (
                            <View className='shopMsg'>
                                {/* 如果有规格则优先显示规格价格 */}
                                <Text className='money'>￥{goodsInfo.skuList[0].salePrice}</Text>
                                {/* 判断是否有单位 */goodsInfo.unitName ? <Text>/{goodsInfo.unitName}</Text> : ''}
                            </View>
                        ) : pinTuanAll == -1 ? (
                           /* 积分活动 */
                           <View className='shopMsg'>
                                <Text className='money'>￥{goodsInfo.skuList[0].salePrice}</Text>
                                {/* 判断是否有单位 */goodsInfo.unitName ? <Text>/{goodsInfo.unitName}</Text> : ''}
                                <Text className='score'>+{goodsInfo.intNum}积分</Text>
                                <Text className='del'>原价:￥{goodsInfo.skuList[0].oldPrice ? goodsInfo.skuList[0].oldPrice : goodsInfo.skuList[0].salePrice}</Text>
                            </View>
                        ) : pinTuanAll == 10 ? (
                            sType == 'pinTuan' && pinTuanData ? (
                                /* 拼团 */
                                <View className='shopMsg'>
                                    <Text className='money'>￥{goodsInfo.skuList[0].salePrice}</Text>
                                    {/* 判断是否有单位 */goodsInfo.unitName ? <Text>/{goodsInfo.unitName}</Text> : ''}
                                    <Text className='del'>原价:￥{goodsInfo.skuList[0].oldPrice ? goodsInfo.skuList[0].oldPrice : goodsInfo.skuList[0].salePrice}</Text>
                                </View>
                            ) : (
                                    <View className='shopMsg'>
                                        {/* 如果有规格则优先显示规格价格 */}
                                        <Text className='money'>￥{goodsInfo.skuList[0].salePrice}</Text>
                                        {/* 判断是否有单位 */goodsInfo.unitName ? <Text>/{goodsInfo.unitName}</Text> : ''}
                                    </View>
                                )
                        ) : pinTuanAll == 2 ? (
                            /* 打折 */
                            <View className='shopMsg'>
                                <Text className='money'>￥{goodsInfo.skuList[0].salePrice}</Text>
                                {/* 判断是否有单位 */goodsInfo.unitName ? <Text>/{goodsInfo.unitName}</Text> : ''}
                                <Text className='del'>原价:￥{goodsInfo.skuList[0].oldPrice ? goodsInfo.skuList[0].oldPrice : goodsInfo.skuList[0].salePrice}</Text>
                            </View>
                        ) :''
                    }
                    {
                        pinTuanData ? (
                            <View className='scopeShow'>
                                <Text>已售:{goodsInfo.saleCount} / 剩余:{goodsInfo.stock}</Text>
                            </View>
                        ) : (
                                <View className='scopeShow'>
                                    {
                                        sType == 'pinTuan' && pinTuanData ? (
                                            <Text>
                                                已拼:{pinTuanData.ptJoinNum} 
                                            </Text>
                                        ) : (
                                                <Text>
                                                    已售:{goodsInfo.saleCount} / 剩余:{goodsInfo.stock}
                                                </Text>
                                            )
                                    }
                                </View>
                            )
                    }
                    {
                        /* 当前拼团的团队显示 */
                        pinTuanAll == 10 ? (
                            /* 拼团数据加载出来的时候 */
                            goodsInfo.ptOverStock == 1 && goodsInfo.ptCount.length > 0 ? (
                                /* 有拼团数据，并且拼团数据大于零的时候 */
                                <View >
                                    <List onLyClick={this.showPinTuanModal.bind(this)} icon='' title='当前1个拼团，点击查看可直接参与' rightTxt='查看' />
                                    <PinTuanModal pinTuanAll={pinTuanData} onGetScope={this.getPinTuanModal.bind(this)} onPinTuan={this.joinPinTuan.bind(this)} />
                                </View>
                            ) : ''
                        ) : ''
                    }
                    {
                        activeArr.length > 0 ? (
                            /* 活动栏目 */
                            <View className='active'>
                                <View className='left'>
                                    <View className='actItem'>
                                        <View className='name'>促销</View>
                                    </View>
                                    <View className='actItem'>
                                        {
                                            activeArr.length > 0 ? activeArr.map((val, i) => (
                                                <View key={'arr' + i} className='title'>{val.actName}</View>
                                            )) : ''
                                        }
                                    </View>
                                </View>
                                <Text></Text>
                            </View>
                        ) : ''
                    }
                </View >
                <Tabs onTabChange={this.tabChange.bind(this)} />
                    <View className='goodsRichText-bar'>
                    {tabsNum == 0 && 
                        <Block>
                            {richTxt ? <RichText className='goodsRichText' nodes={richTxt}></RichText> : <View className='no-data'>暂无详情</View>}
                        </Block>
                    }
                    {tabsNum == 1 && 
                        <View className=''>
                            <Comment goodsId={goodsInfo.goodsDefaultId} />
                        </View>
                    }
                </View>
                {/* 底部购买栏 */}
                <AddCart goodsInfo={goodsInfo} salemodel={salemodel} pinTuanData={sType == 'pinTuan' ? pinTuanData : null} onChoose={this.onChoose.bind(this)} />
                {/* 结算订单组件 */}
                <GoodsClose onGetScope={this.getShopClose.bind(this)} goodsInfo={goodsInfo} onGetGoodsDatilsGG={this.getGoodsDatilsGG.bind(this)} />
                <Authorize page='onSetUserInfo' onSetUserInfo={this.getIsLogin.bind(this)}></Authorize>
            </View >
        )
    }
}

